package com.be.beadmin.service.config;

import com.be.beadmin.service.task.TaskRejectedHandler;
import com.be.beadmin.service.task.TaskThreadPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 *  @Description 创建数据源
 *  @author xunzhang
 *  @Date 2020.08.30 13:34
 */
@Component
public class CommonBeanFactory {

	private Logger logger = LoggerFactory.getLogger(this.getClass());


	@Bean
	public InitializingBean initializingBean() {
		return () -> SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL);
	}

	
	/**
	 * 构建任务执行线程池
	 * @param threadPoolConfig 线程池配置信息
	 * @return 任务执行线程池
	 */
	@Bean
	@ConditionalOnProperty(name = "thread.pool.open", havingValue = "true")
	public TaskThreadPool taskThreadPool(ThreadPoolConfig threadPoolConfig) {
		TaskThreadPool taskThreadPool = new TaskThreadPool(
				threadPoolConfig.getCorePoolSize(), // 50
				threadPoolConfig.getMaximumPoolSize(), // 100
				threadPoolConfig.getKeepAliveTime(), // 3
				TimeUnit.SECONDS,
				new LinkedBlockingQueue<>(threadPoolConfig.getThreadQueueSize()), // 2000
				new TaskRejectedHandler()); // 自定义， 直接丢弃任务，并打印日志
		logger.info("构建[ TaskThreadPool ]线程池成功");
		return taskThreadPool;
	}
}
